package keter.rabbitmq.log;

import com.rabbitmq.client.*;

import java.io.IOException;

public class LogTopicRecv {

  /** RabbitMQ内嵌日志交换器*/
  private static final String LOGS_EXCHANGE = "amq.rabbitmq.log";

  /** 日志交换器内嵌 binding-key */
  private static String INFO_BINDING_KEY = "info";
  private static String ERROR_BINDING_KEY = "error";

  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("192.168.1.100");
    factory.setUsername("haha");
    factory.setPassword("haha");

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    bindAndConsume(channel, INFO_BINDING_KEY);
    bindAndConsume(channel, ERROR_BINDING_KEY);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
  }

  private static void bindAndConsume(Channel channel, String bindingKey) throws IOException {
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, LOGS_EXCHANGE, bindingKey);
    channel.basicConsume(
        queueName,
        true,
        new DefaultConsumer(channel) {
          @Override
          public void handleDelivery(
              String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
              throws IOException {
            String message = new String(body, "UTF-8");
            System.out.println("[" + envelope.getRoutingKey() + "]:'" + message + "'");
          }
        });
  }
}
